import React, { useState, useEffect } from 'react';
import dayjs from 'dayjs';
import JournalInput from './components/JournalInput';
import { Card, DatePicker, Popup, Button, Dialog, Popover } from 'antd-mobile';
import { BrowserRouter, Routes, Route, NavLink } from 'react-router-dom';
import SearchPage from './pages/SearchPage';
import AnalysisPage from './pages/AnalysisPage';
import LoginPage from './pages/LoginPage';
import axios from './axiosInstance';

import 'antd-mobile/es/global';

function App() {
  const [entries, setEntries] = useState([]);
  const [aiAnswer, setAiAnswer] = useState('');
  const [visible, setVisible] = useState(false);
  const [date, setDate] = useState();
  const [deleteId, setDeleteId] = useState(null);
  const [username, setUsername] = useState(localStorage.getItem('username') || '');

  const fetchEntries = async () => {
    const res = await axios.get('/journals');
    const sorted = res.data
      .filter(entry => entry.created_at)
      .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
      .slice(0, 10);
    setEntries(sorted);
  };

  useEffect(() => {
    if (username) fetchEntries();
  }, [username]);

  const handleSubmit = async (content) => {
    const res = await axios.post('/journals', { content });
    if (res.data.status === 'qa') {
      setAiAnswer(res.data.answer);
    } else {
      setAiAnswer('');
      fetchEntries();
    }
  };

  const handleDelete = async (id) => {
    await axios.delete(`/journals/${id}`);
    setDeleteId(null);
    fetchEntries();
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    setUsername('');
  };

  if (!username) {
    return <LoginPage onLogin={setUsername} />;
  }

  return (
    <BrowserRouter>
      <div style={{
        padding: '12px',
        width: '100%',
        minHeight: '100vh',
        boxSizing: 'border-box',
        background: '#f5f5f5',
        overflowX: 'hidden'
      }}>
        <div style={{
          margin: '0 0 16px',
          padding: '12px',
          background: '#fff',
          borderRadius: '8px',
          boxShadow: '0 1px 2px rgba(0,0,0,0.1)',
          fontSize: '16px'
        }}>
          <div style={{
            display: 'flex',
            flexDirection: 'column',
            gap: '12px'
          }}>
            <div style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              fontWeight: 600,
              fontSize: '18px',
              color: '#333'
            }}>
              <span>AI 日记助手</span>
              <div style={{
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                fontSize: '14px',
                color: '#666'
              }}>
                <span>{username}</span>
                <Button
                  size="mini"
                  onClick={handleLogout}
                  style={{
                    fontSize: '13px',
                    padding: '4px 8px'
                  }}
                >
                  退出
                </Button>
              </div>
            </div>
            <div style={{
              display: 'flex',
              gap: '12px',
              fontSize: '15px'
            }}>
              <NavLink to="/" style={({ isActive }) => ({
                color: isActive ? '#1677ff' : '#666',
                textDecoration: 'none'
              })}>首页</NavLink>
              <span style={{ color: '#ddd' }}>|</span>
              <NavLink to="/search" style={({ isActive }) => ({
                color: isActive ? '#1677ff' : '#666',
                textDecoration: 'none'
              })}>日记查询</NavLink>
              <span style={{ color: '#ddd' }}>|</span>
              <NavLink to="/analysis" style={({ isActive }) => ({
                color: isActive ? '#1677ff' : '#666',
                textDecoration: 'none'
              })}>日记整理</NavLink>
            </div>
            <div style={{
              fontSize: '14px',
              color: '#666',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between'
            }}>
            </div>
          </div>
        </div>

        <div style={{ flex: 1 }}>
          <Routes>
            <Route path="/" element={
              <>
                <JournalInput onSubmit={handleSubmit} />
                {aiAnswer && (
                  <Card style={{
                    margin: '16px 0',
                    background: '#f6f6f6',
                    fontSize: '15px',
                    lineHeight: 1.6
                  }}>
                    <strong>AI答复：</strong> {aiAnswer}
                  </Card>
                )}
                <h4 style={{
                  margin: '20px 0 12px',
                  fontSize: '16px',
                  color: '#333'
                }}>
                  近期摘要（最多10条）：
                </h4>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                  {entries.map((entry) => (
                    <Card key={entry.id} style={{
                      fontSize: '15px',
                      lineHeight: 1.6
                    }}>
                      <div style={{
                        display: 'flex',
                        flexDirection: 'column',
                        gap: '8px'
                      }}>
                        <div style={{
                          display: 'flex',
                          justifyContent: 'space-between',
                          alignItems: 'center',
                          borderBottom: '1px solid #f0f0f0',
                          paddingBottom: '8px',
                          marginBottom: '4px'
                        }}>
                          <div style={{
                            color: '#666',
                            fontSize: '13px'
                          }}>
                            {dayjs(entry.created_at).format('YYYY-MM-DD HH:mm:ss')}
                          </div>
                          <Popover
                            visible={deleteId === entry.id}
                            onVisibleChange={v => setDeleteId(v ? entry.id : null)}
                            content={
                              <div style={{ padding: '12px', fontSize: '14px' }}>
                                <div style={{ marginBottom: '12px' }}>确定要删除这条日记吗？</div>
                                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
                                  <Button size="mini" onClick={() => setDeleteId(null)}>取消</Button>
                                  <Button size="mini" color="danger" onClick={() => handleDelete(entry.id)}>删除</Button>
                                </div>
                              </div>
                            }
                            placement="left"
                            trigger="click"
                          >
                            <Button
                              size="mini"
                              style={{
                                minWidth: '60px',
                                color: '#e8313e',
                                fontSize: '13px',
                                padding: '4px 8px'
                              }}
                            >
                              删除
                            </Button>
                          </Popover>
                        </div>
                        <div style={{
                          color: '#333',
                          fontSize: '15px',
                          lineHeight: 1.6,
                          wordBreak: 'break-word'
                        }}>
                          {entry.summary}
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              </>
            } />
            <Route path="/search" element={<SearchPage />} />
            <Route path="/analysis" element={<AnalysisPage />} />
          </Routes>
        </div>
      </div>
    </BrowserRouter>
  );
}

export default App;